import { useEffect, useState } from "react";
import style from "./index.module.scss";
import { Overlay, Toast } from "react-vant";
import giftCat from "@/assets/images/cats-eat-fish/gift-cat.png";
import giftFail from "@/assets/images/cats-eat-fish/gift-fail.png";
import classNames from "classnames";
import TencentCloudChat from "@tencentcloud/chat";

const BaseUrl =
  process.env.REACT_APP_ENV === "prod"
    ? "https://webapi.pupupal.com"
    : "https://kk-test-webapi.sayhaiapp.com";

// import TIMUploadPlugin from "tim-upload-plugin";

let options = {
  SDKAppID: process.env.REACT_APP_ENV === "prod" ? 1600029348 : 1600021454, // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
};

// 创建 SDK 实例
// `TencentCloudChat.create()` 方法对于同一个 `SDKAppID` 只会返回同一份实例
// SDK 实例通常用 chat 表示
let chat = TencentCloudChat.create(options);

// 设置 SDK 日志级别
// 0: 普通级别，日志量较多，接入时建议使用
// 1: release 级别，SDK 输出关键信息，生产环境时建议使用
chat.setLogLevel(0);
// chat.setLogLevel(1);

// 注册腾讯云即时通信 IM 上传插件
// chat.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin });

const Record = ({ showModal, giftInfo }) => {
  const urlParams = new URLSearchParams(window.location.search);
  const authorizationToken = urlParams.get("userId");
  // console.log("authorizationToken", authorizationToken);
  const [userId, setUserId] = useState("");
  const [userSig, setUserSig] = useState("");
  const [show, setShow] = useState(false);
  const [data, setData] = useState({
    // 已存入您的礼物背包
    messageUp: "",
    giftPicture: giftFail,
    messageDown: "招财猫与您擦肩而过",
  });
  const getData = async () => {
    let url = `/user/notification/user-sig`;
    fetch(BaseUrl + url, {
      method: "GET",
      headers: {
        Authorization: authorizationToken,
      },
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.code === 200 && response.data) {
          setUserSig(response.data || "");
        } else {
          console.error("Failed to fetch ranking data:", response.msg);
          Toast.info(response.msg);
        }
      })
      .catch((error) => console.error("Error fetching ranking data:", error));
  };

  const getUserInfo = async () => {
    let url = `/user/user/info`;
    fetch(BaseUrl + url, {
      method: "POST",
      headers: {
        Authorization: authorizationToken,
      },
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.code === 200 && response.data) {
          setUserId(response.data?.userId || "");
        } else {
          Toast.info(response.msg);
        }
      })
      .catch((error) => console.error("Error fetching ranking data:", error));
  };

  useEffect(() => {
    if (authorizationToken) {
      getData();
      getUserInfo();
    } else {
      console.error("Authorization token not found in URL");
    }
  }, []);

  useEffect(() => {
    console.log("----------", userId, userSig);
    if (userId && userSig) {
      // 登录
      chat
        .login({ userID: `${userId}`, userSig: userSig })
        .then((res) => {
          console.log("登录成功", res);
        })
        .catch((err) => {
          console.log("err:", err);
        });
    }
  }, [userId, userSig]);

  const onMessageReceived = function (event) {
    // event.data - 存储 Message 对象的数组 - [Message]
    // Message 数据结构详情请参考 https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html
    console.log("onMessageReceived", event);

    // event.data - 存储消息已读回执信息的数组
    const readReceiptInfoList = event.data;
    readReceiptInfoList.forEach((item) => {
      const { from, conversationID, payload, messageID, to } = item;
      if (from === "LuckCatMessage" && to === `${userId}`) {
        console.log("message", JSON.parse(payload?.text));
        const res = JSON.parse(payload?.text);
        setData(res);
        setShow(true);
      }
      // const message = chat.findMessage(messageID);
    });

    // const message = chat.findMessage("messageID");
  };
  chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);

  return (
    <div className={style.giftWrap}>
      <Overlay visible={show}>
        <div
          className={classNames(style.messageBox, true ? style.bgS : style.bgF)}
        >
          <div className={style.giftContent}>
            <p className={style.p1}>{data?.messageUp}</p>
            <img className={style.gift} src={data?.giftPicture || giftFail} />
            <div className={style.p2}>
              <p>{data?.messageDown}</p>
              {/* <p>并额外获得了9999个蓝钻</p> */}
            </div>
            <div className={style.btn} onClick={() => setShow(false)}></div>
          </div>
        </div>
      </Overlay>
    </div>
  );
};

export default Record;
